<template>
    <div>
      <h1>表格展示</h1>
      <table>
        <thead>
          <tr>
            <th v-for="header in headers" :key="header">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in paginatedData" :key="row[0]">
            <td v-for="cell in row" :key="cell">{{ cell }}</td>
          </tr>
        </tbody>
      </table>
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        data: [],  // 存储从后端获取的数据
        currentPage: 1,  // 当前页码
        itemsPerPage: 10  // 每页显示的条目数
      };
    },
    computed: {
      headers() {
        return this.data.length > 0 ? this.data[0] : [];
      },
      rows() {
        return this.data.length > 1 ? this.data.slice(1) : [];
      },
      totalPages() {
        return Math.ceil(this.rows.length / this.itemsPerPage);
      },
      paginatedData() {
        const start = (this.currentPage - 1) * this.itemsPerPage;
        const end = start + this.itemsPerPage;
        return this.rows.slice(start, end);
      }
    },
    methods: {
      fetchData() {
        axios.get('http://localhost:5000/data')  // 从后端获取数据
          .then(response => {
            this.data = response.data;  // 将数据存储在 data 属性中
          })
          .catch(error => {
            console.error("Error fetching data:", error);  // 错误处理
          });
      },
      prevPage() {
        if (this.currentPage > 1) {
          this.currentPage--;
        }
      },
      nextPage() {
        if (this.currentPage < this.totalPages) {
          this.currentPage++;
        }
      }
    },
    created() {
      this.fetchData();  // 页面加载时获取数据
    }
  };
  </script>
  
  <style>
  table {
    width: 100%;
    border-collapse: collapse;
  }
  th, td {
    border: 1px solid black;
    padding: 8px;
    text-align: left;
  }
  button {
    margin: 5px;
  }
  </style>
  